<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input
        class="filter-item"
        placeholder="输入关键字进行过滤"
        v-model="listQuery.keyword"
        style="width: 30%"
      >
      </el-input>
      <!--      <el-input v-model="listQuery.title" placeholder="Title" style="width: 200px;" class="filter-item"-->
      <!--                @keyup.enter.native="handleFilter"-->
      <!--      />-->
      <!--      <el-select v-model="listQuery.importance" placeholder="Imp" clearable style="width: 90px" class="filter-item">-->
      <!--        <el-option v-for="item in importanceOptions" :key="item" :label="item" :value="item" />-->
      <!--      </el-select>-->
      <!--      <el-select v-model="listQuery.type" placeholder="Type" clearable class="filter-item" style="width: 130px">-->
      <!--        <el-option v-for="item in calendarTypeOptions" :key="item.key" :label="item.display_name+'('+item.key+')'" :value="item.key" />-->
      <!--      </el-select>-->
      <!--      <el-select v-model="listQuery.sort" style="width: 140px" class="filter-item" @change="handleFilter">-->
      <!--        <el-option v-for="item in sortOptions" :key="item.key" :label="item.label" :value="item.key" />-->
      <!--      </el-select>-->
      <el-button class="filter-item" type="primary" icon="el-icon-search" @click="getList"
                 style="margin-left: 10px"
      >
        搜索
      </el-button>
      <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-edit"
                 @click="handleCreate"
      >
        添加试卷
      </el-button>
      <!--      <el-button v-waves :loading="downloadLoading" class="filter-item" type="primary" icon="el-icon-download"-->
      <!--                 @click="handleDownload"-->
      <!--      >-->
      <!--        导出-->
      <!--      </el-button>-->
      <!--      <el-checkbox v-model="showReviewer" class="filter-item" style="margin-left:15px;" @change="tableKey=tableKey+1">-->
      <!--        审核-->
      <!--      </el-checkbox>-->
    </div>
    <el-table v-loading="listLoading" :data="list" border fit highlight-current-row style="width: 100%">
      <el-table-column align="center" label="ID" min-width="40">
        <template slot-scope="scope">
          <span>{{ scope.row.id }}</span>
        </template>
      </el-table-column>

      <el-table-column min-width="140" align="center" label="试卷名称">
        <template slot-scope="scope">
          <span>{{ scope.row.name }}</span>
          <!--          <span>{{ scope.row.timestamp | parseTime('{y}-{m}-{d} {h}:{i}') }}</span>-->
        </template>
      </el-table-column>

      <el-table-column min-width="140px" align="center" label="难度">
        <template slot-scope="scope">
          <el-rate
            v-model="scope.row.difficulty"
            :texts="text"
            disabled
            show-text
            text-color="#ccc"
            :colors="['#99A9BF', '#F7BA2A', '#FF9900']"
          >
          </el-rate>
        </template>
      </el-table-column>

      <el-table-column min-width="60" align="center" label="总分">
        <template slot-scope="scope">
          <el-tag>{{ scope.row.score }}</el-tag>
          <!--          <span>{{ scope.row.timestamp | parseTime('{y}-{m}-{d} {h}:{i}') }}</span>-->
        </template>
      </el-table-column>

      <el-table-column min-width="60" align="center" label="及格分">
        <template slot-scope="scope">
          <el-tag>{{ scope.row.pass_score }}</el-tag>
          <!--          <span>{{ scope.row.timestamp | parseTime('{y}-{m}-{d} {h}:{i}') }}</span>-->
        </template>
      </el-table-column>

      <el-table-column min-width="80px" align="center" label="状态">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.status"
            :active-value="1"
            :inactive-value="0"
            @change="changeStatus($event,scope.row.id)"
          >
          </el-switch>
          <!--          <span>{{ scope.row.timestamp | parseTime('{y}-{m}-{d} {h}:{i}') }}</span>-->
        </template>
      </el-table-column>

      <el-table-column min-width="100" align="center" label="创建时间">
        <template slot-scope="scope">
          <span>{{ scope.row.created_at }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="操作" min-width="100" fixed="right">
        <template slot-scope="scope">
          <el-button type="primary" size="small" icon="el-icon-edit" circle @click="handleUpdate(scope.row)">
          </el-button>
          <el-button type="danger" size="small" icon="el-icon-delete" circle @click="del(scope.row.id)">
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit"
                @pagination="getList"
    />

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" width="80%">
      <el-form ref="dataForm" :rules="rules" :model="temp" label-position="left" label-width="120px"
               style="width:80%; margin-left:50px;"
      >
        <el-form-item label="试卷名称" prop="name">
          <el-input v-model="temp.name"/>
        </el-form-item>

        <el-form-item label="及格分数">
          <el-input v-model="temp.pass_score" type="number"/>
        </el-form-item>

        <el-form-item label="状态">
          <el-switch
            v-model="temp.status"
            :active-value="1"
            :inactive-value="0"
          ></el-switch>
        </el-form-item>
        <el-form-item label="难易度">
          <el-rate
            style="margin-top:10px"
            text-color="#ccc"
            :texts="text"
            v-model="temp.difficulty"
            show-text
            :colors="colors">
          </el-rate>
        </el-form-item>
        <el-form-item label="筛选考题">
          <el-input
            placeholder="输入题干进行过滤"
            v-model="filterText"
          ></el-input>
        </el-form-item>
        <el-form-item label="已选择"><el-tag>{{judge_count}}判断题</el-tag>&nbsp;
          <el-tag>{{one_choose_count}}单选题</el-tag>&nbsp;
          <el-tag>{{choose_count}}多选题</el-tag>&nbsp;
          <el-tag>{{easy_count}}简答题</el-tag>&nbsp;
          <el-tag>{{explain_count}}名词解释</el-tag>&nbsp;
          <el-tag>{{essay_count}}论述题</el-tag>&nbsp;
          <el-tag>{{calculate_count}}计算题</el-tag>&nbsp;
          <el-tag type="success">总分{{score}}</el-tag>
        </el-form-item>
        <el-form-item label="选择考题">
          <el-tree
            :data="menus"
            :checkStrictly=false
            node-key="id"
            :highlight-current="true"
            :expand-on-click-node="true"
            :props="defaultProps"
            ref="tree"
            show-checkbox
            :filter-node-method="filterNode"
            @check-change="changeCheck"
            :default-checked-keys="checked_ques"
          >
        <span class="custom-tree-node" slot-scope="{ node, data }">
        <span>{{ node.label }}</span>
        <span>
<!--          已选择n条-->
          <el-button
            type="text"
            size="mini"
            @click="() => append(data)"
          >
            <span v-if="data.level == 3">{{data.score?data.score+'/分':'设置'}}</span>
            <span v-else>{{data.score?'每题分数为:'+data.score+'/分':'批量设置'}}</span>
          </el-button>
                    <el-button
                      type="text"
                      size="mini"
                      @click="() => sorted(data)"
                    >
            <span v-if="data.level == 3">{{data.sort?'第'+data.sort+'题':'排序'}}</span>
          </el-button>
        </span>
      </span>
          </el-tree>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <center>
          <el-button @click="resetForm">
            取消
          </el-button>
          <el-button type="primary" @click="dialogStatus==='create'?createData():createData()">
            生成试卷
          </el-button>
        </center>
      </div>
    </el-dialog>
    <el-dialog title="设置分数" :visible.sync="dialogScoreVisible" width="40%">
      <el-input type="number" v-model="score"/>
      <div slot="footer" class="dialog-footer">
        <center>
          <el-button @click="resetForm">
            取消
          </el-button>
          <el-button type="primary" @click="saveScore">
            确定
          </el-button>
        </center>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { create, getList, changeStatus, del} from '@/api/test'
import Pagination from '@/components/Pagination'
import { getAll } from '@/api/questions'
import store from '@/store'
import router from '@/router' // Secondary package based on el-pagination

export default {
  name: 'RolesList',
  components: { Pagination },
  filters: {
    statusFilter(status) {
      const statusMap = {
        published: 'success',
        draft: 'info',
        deleted: 'danger'
      }
      return statusMap[status]
    }
  },
  data() {
    return {
      dialogScoreVisible:false,
      menus: [],
      list: null,
      total: 0,
      listLoading: true,
      listQuery: {
        page: 1,
        limit: 20,
        keyword: ''
      },
      checked_ques:[],
      judge_count:0,
      one_choose_count:0,
      choose_count:0,
      easy_count:0,
      explain_count:0,
      essay_count:0,
      calculate_count:0,
      score:0,
      colors: ['#99A9BF', '#F7BA2A', '#FF9900'],
      temp: {
        id: undefined,
        name: '',
        questions: [],
        status:1,
        score:0,
        difficulty:0,
        pass_score:0
      },
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '编辑',
        create: '创建'
      },
      filterText: '',
      defaultProps: {
        children: 'children',
        label: 'label'
      },
      text: ['入门', '初级', '中等', '困难', '灾难'],
      rules: {
        name: [{ required: true, message: '试卷名称不能为空', trigger: 'change' }]
      }
    }
  },
  watch: {
    filterText(val) {
      this.$refs.tree.filter(val)
    },
  },
  created() {
    this.getList()
    this.getMenus()
  },
  methods: {
    filterNode(value, data) {
      if (!value) return true
      return data.label.indexOf(value) !== -1
    },
    changeCheck(){
      this.score = 0
      this.judge_count=0
      this.one_choose_count=0
      this.choose_count=0
      this.easy_count=0
      this.explain_count=0
      this.essay_count=0
      this.calculate_count=0
      let data = this.$refs.tree.getCheckedNodes()
      for(var i in data){
        if(data[i]['level'] == 3){
          if(data[i].score){
            this.score += data[i].score
          }
          switch(data[i]['type']){
            case 'judge':
              this.judge_count++
              break;
            case 'one_choose':
              this.one_choose_count++
              break;
            case 'choose':
              this.choose_count++
              break;
            case 'easy':
              this.easy_count++
              break;
            case 'explain':
              this.explain_count++
              break;
            case 'essay':
              this.essay_count++
              break;
            case 'calculate':
              this.calculate++
              break;
          }
        }
      }
    },
    getCheckedNodes() {
      console.log(this.$refs.tree.getCheckedNodes())
    },
    setCheckedNodes(row) {
      this.$refs.tree.setCheckedNodes(row);
    },
    getMenus() {
      getAll().then(response => {
        this.menus = response.data
        // Just to simulate the time of the request
        setTimeout(() => {
          this.listLoading = false
        }, 1.5 * 1000)
      })
    },
    getList() {
      this.listLoading = true
      getList(this.listQuery).then(response => {
        this.list = response.data
        this.total = response.total
        this.listLoading = false

      })
    },
    resetForm(){
      this.dialogFormVisible = false
      this.$refs.tree.setCheckedKeys([]);
    },
    handleCreate() {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      this.temp.questions = this.$refs.tree.getCheckedNodes();
      this.temp.score = this.score
      for(var i in this.temp.questions){
        if(this.temp.questions[i]['level'] != 3){
            this.temp.questions.splice(i, 1)
        }else{
          if(!this.temp.questions[i].hasOwnProperty('score') || !this.temp.questions[i].hasOwnProperty('sort')){
            this.$message({
              type: 'success',
              message: '请先设置《'+this.temp.questions[i]['label']+'》的分数或排序'
            });
            return '';
          }
        }
      }
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          create(this.temp).then(response => {
            // this.list.unshift(this.temp)
            this.dialogFormVisible = false
            if (response.code == 200) {
              this.$notify.success({
                title: '成功',
                message: response.msg,
                type: 'success',
                duration: 2000
              })
              this.resetTemp()
              this.getList()
            } else {
              this.$notify.error({
                title: '失败',
                message: response.msg,
                duration: 2000
              })
            }
          })
        }
      })
    },
    handleUpdate(row) {
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.temp = Object.assign({}, row) // copy obj
      this.checked_ques =[]
      // for(var i in row.questions){
      //   this.checked_ques.push(row.questions[i].id)
      // }
      this.judge_count=0
      this.one_choose_count=0
      this.choose_count=0
      this.easy_count=0
      this.explain_count=0
      this.essay_count=0
      this.calculate_count=0
      this.score = 0
      for(var l in row.questions){
        if(row.questions[l].score){
          this.score +=row.questions[l].score
        }
        switch(row.questions[l]['type']){
          case 'judge':
            this.judge_count++
            break;
          case 'one_choose':
            this.one_choose_count++
            break;
          case 'choose':
            this.choose_count++
            break;
          case 'easy':
            this.easy_count++
            break;
          case 'explain':
            this.explain_count++
            break;
          case 'essay':
            this.essay_count++
            break;
          case 'calculate':
            this.calculate++
            break;
        }
        for(var i in this.menus){
          if(this.menus[i]['children']){
            for(var j in this.menus[i]['children']){
              if(this.menus[i]['children'][j]['children']){
                for(var k in this.menus[i]['children'][j]['children']){
                  if(this.menus[i]['children'][j]['children'][k]['id'] == row.questions[l]['id']){
                    // this.menus[i]['children'][j]['children'][k]['score'] = row.questions[l]['score']
                    this.$set(this.menus[i]['children'][j]['children'][k], 'score',row.questions[l]['score'])
                    this.$set( this.menus[i]['children'][j]['children'][k],'sort', row.questions[l]['sort'])
                  }
                }
              }
            }
          }
        }
        this.checked_ques.push(row.questions[l].id)
      }
      // this.$refs.tree.setCheckedNodes(row.questions);
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    del(id) {
      this.$confirm('确认要删除该条数据吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        del(id).then(response => {
          // this.list.unshift(this.temp)
          if (response.code == 200) {
            this.$notify.success({
              title: '成功',
              message: response.msg,
              type: 'success',
              duration: 2000
            })
            this.resetTemp()
            this.getList()
          } else {
            this.$notify.error({
              title: '失败',
              message: response.msg,
              duration: 2000
            })
          }
        })
      }).catch(() => {

      })
    },
    append(data) {
      this.$prompt('请输入分数', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputPattern: /^[0-9]*$/,
        inputErrorMessage: '格式不正确',
      }).then(({ value }) => {
        value = parseInt(value)
        if(data.level == 1){
          for(var i in data.children){
            this.$set(data.children[i], 'score', value)
            for(var j in data.children[i]['children']){
              // data.children[i]['children'][j]['score']
              this.$set(data.children[i]['children'][j], 'score', value)
            }
          }
        }else if(data.level == 2){
          for(var i in data.children){
            this.$set(data.children[i], 'score', value)
          }
        }
        this.$set(data, 'score', value)
        this.score = 0
        this.judge_count=0
        this.one_choose_count=0
        this.choose_count=0
        this.easy_count=0
        this.explain_count=0
        this.essay_count=0
        this.calculate_count=0
        let tongji = this.$refs.tree.getCheckedNodes()
        for(var i in tongji){
          if(tongji[i]['level'] == 3){
            if(tongji[i].score){
              this.score += tongji[i].score
            }
            switch(tongji[i]['type']){
              case 'judge':
                this.judge_count++
                break;
              case 'one_choose':
                this.one_choose_count++
                break;
              case 'choose':
                this.choose_count++
                break;
              case 'easy':
                this.easy_count++
                break;
              case 'explain':
                this.explain_count++
                break;
              case 'essay':
                this.essay_count++
                break;
              case 'calculate':
                this.calculate++
                break;
            }
          }
        }
        this.$message({
          type: 'success',
          message: '设置成功'
        });
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '取消输入'
        });
      });
    },


    sorted(data) {
      this.$prompt('请输入第几题', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputPattern: /^[0-9]*$/,
        inputErrorMessage: '格式不正确',
      }).then(({ value }) => {
        value = parseInt(value)
        this.$set(data, 'sort', value)
        this.$message({
          type: 'success',
          message: '设置成功'
        });
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '取消输入'
        });
      });
    },


    saveScore(){
      this.$set(data, 'children', this.score);
    },
    changeStatus(val, id) {
      changeStatus(val, id).then(response => {
        this.$notify.success({
          title: '消息提示',
          message: response.msg,
          offset: 100
        })
      })
    },
    resetTemp() {
      this.temp = {
        id: undefined,
        name: '',
        questions:[],
        score:0,
        status:1,
        pass_score:0
      }
    }
  }
}
</script>

<style scoped>
.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;
}
.edit-input {
  padding-right: 100px;
}

.cancel-btn {
  position: absolute;
  right: 15px;
  top: 10px;
}
</style>
